<template>
    <div class="app-container">
        <div class="cardbg">
            <div class="card">

                <el-row style="height: 30px;" align="middle">
                    <div
                        style="width: 6px; height:20px;background-color:#2984f8;border-radius: 5px;margin-right: 10px;">
                    </div>
                    <span style="font-size: 18px;">数据概况</span>
                </el-row>
                <!-- 筛选项 -->
                <el-date-picker v-model="value1" type="daterange" range-separator="To" start-placeholder="Start date"
                    end-placeholder="End date" size="large" value-format="YYYY-MM-DD" />
                <div class="ca" id="borkenline" style="width: 100%; height: 500px;"></div>


                <div style="width: 100%;display: flex; justify-content: space-around;padding: 30px;">
                    <div class="ca residentage">
                        <span>居民年龄</span>
                        <div class="resi" id="residentage"></div>
                    </div>
                    <div class="ca residentage">
                        <span>居民文化</span>
                        <div class="resi" id="residentculture"></div>
                    </div>
                    <div class="ca residentage">
                        <span>居民性别</span>
                        <div class="resi" id="residentsex"></div>
                    </div>

                </div>
                <div style="height: 400px; width: 100%;display: flex; justify-content: space-around;padding: 30px;">
                    <div class="ca residentage" style="height: 400px;">
               
                 <div class="resi" id="residenttag"></div>

                    </div>
                    <div class="ca residentage" style="width: 50%;height: 400px;">
               
               <div class="resi" id="residentservicepackageuse"></div>

                  </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script setup>
const format = (percentage) => (percentage === 100 ? 'Full' : `${percentage}%`)
import { getresidentservicepackageuse,getresidenttag, getresidentsex, getdataservice, getdataserviceitem, getresidentage, getresidentculture } from '@/api/resident/resident.js'
const value1 = ref('')
// 生成日期范围
function generateDateRange(dateArray) {
    if (dateArray.length !== 2) {
        throw new Error('日期数组必须包含两个日期');
    }

    const startDate = new Date(dateArray[0]);
    const endDate = new Date(dateArray[1]);

    if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) {
        throw new Error('日期格式无效');
    }

    const result = [];
    const currentDate = new Date(startDate);

    while (currentDate <= endDate) {
        const month = String(currentDate.getMonth() + 1).padStart(2, '0');
        const day = String(currentDate.getDate()).padStart(2, '0');
        result.push(`${month}/${day}`);
        currentDate.setDate(currentDate.getDate() + 1);
    }

    return result;
}
//日期范围
let dateRange = ref([]);

// 监听 value1 的变化
watch(value1, async (newValue, oldValue) => {
    console.log('value1 发生变化，旧值: ', oldValue, '新值: ', newValue);
    if (newValue) {
        // 当 value1 有值时，重新生成日期范围
        dateRange.value = generateDateRange(newValue);
        console.log('生成的日期范围: ', dateRange.value);
        // 可以在这里添加其他逻辑，比如重新请求数据

        await getdataservicelist({ start: newValue[0], end: newValue[1] })
        await getdataserviceitemlist({ start: newValue[0], end: newValue[1] })
        const numArray = mapNumsToDates(dateRange.value, servicepackage.value);
        console.log('对应签约数量数组:', numArray);
        const itemnumArray = mapNumsToDates(dateRange.value, servicepackageitem.value);
        console.log('对应服务数量数组:', itemnumArray);

        // 填入数据
        borkenline.setOption({
            xAxis: {
                data: dateRange.value
            },
            series: [
                {
                    name: '签约量',
                    type: 'line',
                    stack: 'Total',
                    data: numArray
                },
                {
                    name: '服务量',
                    type: 'line',
                    stack: 'Total',
                    data: itemnumArray
                }
            ]
        });
    }
});
//服务数量
let servicepackage = ref([])
function getdataservicelist(query) {
    return new Promise((resolve, reject) => {
        console.log('query', query);
        getdataservice(query).then(res => {
            console.log('服务数量', res)
            servicepackage.value = res.data
            resolve(res.data)
        }).catch(error => {
            console.error('Error fetching data:', error);
            reject(error);
        })
    })
}
//服务项目数量
let servicepackageitem = ref([])
function getdataserviceitemlist(query) {
    return new Promise((resolve, reject) => {
        getdataserviceitem(query).then(res => {
            console.log('服务项目数量', res)
            servicepackageitem.value = res.data
            resolve(res.data)
        }).catch(error => {
            console.error('Error fetching data:', error);
            reject(error);
        })
    })
}
//居民年龄
let residentagelist = ref([])
function getresidentagelist() {
    return new Promise((resolve, reject) => {
        getresidentage().then(res => {
            console.log('居民年龄', res.data)
            residentagelist.value = res.data
            resolve(res.data)
        }).catch(error => {
            console.error('Error fetching data:', error);
            reject(error);
        })
    })
}
//居民文化
let residentculturelist = ref([])
function getresidentculturelist() {
    return new Promise((resolve, reject) => {
        getresidentculture().then(res => {
            console.log('居民文化', res.data)
            residentculturelist.value = res.data
            resolve(res.data)
        }).catch(error => {
            console.error('Error fetching data:', error);
            reject(error);
        })
    })
}
//性别
let residentsexlist = ref([])
function getresidentsexlist() {
    return new Promise((resolve, reject) => {
        getresidentsex().then(res => {
            console.log('性别', res.data)
            residentsexlist.value = res.data
            resolve(res.data)
        }).catch(error => {
            console.error('Error fetching data:', error);
            reject(error);
        })
    })
}
//标签
let residenttaglist = ref([])
function getresidenttaglist() {
    return new Promise((resolve, reject) => {
        getresidenttag().then(res => {
            console.log('标签', res.data)
            residenttaglist.value = res.data
            console.log('residenttaglist.value',residenttaglist.value);
            resolve(res.data)
        }).catch(error => {
            console.error('Error fetching data:', error);
            reject(error);
        })
    })
}
//服务包
let residentservicepackagelist = ref([])
function getresidentservicepackagelist() {
    return new Promise((resolve, reject) => {
        getresidentservicepackageuse().then(res => {
            console.log('服务包', res.data)
            residentservicepackagelist.value = res.data
            resolve(res.data) 
        }).catch(error=>{
            console.error('Error fetching data:', error);
            reject(error);
        })
    }) 
}

//得到处理数组
function mapNumsToDates(dateRange, dataArray) {
    const numArray = new Array(dateRange.length).fill(0);

    dataArray.forEach(item => {
        const itemDate = new Date(item.time.replace(/-/g, '/'));
        const month = String(itemDate.getMonth() + 1).padStart(2, '0');
        const day = String(itemDate.getDate()).padStart(2, '0');
        const dateStr = `${month}/${day}`;
        const index = dateRange.indexOf(dateStr);

        if (index !== -1) {
            numArray[index] = item.num;
        }
    });

    return numArray;
}

function Processingdata() {

}


//echarts
import * as echarts from 'echarts';
import { ref, watch } from 'vue';
let borkenline;
// 所有组件渲染完成后执行的函数
onMounted(async() => {
    nextTick(async () => {

      



        // 这里编写所有组件渲染完成后要执行的代码
        borkenline = echarts.init(document.getElementById('borkenline'));

        /** @type EChartsOption */
        borkenline.setOption({
            title: {
                text: '数据概况'
            },
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data: ['服务量', '签约量']
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            toolbox: {
                feature: {
                    saveAsImage: {}
                }
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: ['01/01', '01/02', '01/03', '01/04', '01/05', '01/06', '01/07']
            },
            yAxis: {
                type: 'value'
            },
            series: [
                {
                    name: '签约量',
                    type: 'line',
                    stack: 'Total',
                    data: [120, 132, 101, 134, 90, 230, 210]
                },
                {
                    name: '服务量',
                    type: 'line',
                    stack: 'Total',
                    data: [150, 232, 201, 154, 190, 330, 410]
                }
            ]
        })
        //age
        const residentage = echarts.init(document.getElementById('residentage'));
        residentage.setOption({
            tooltip: {
                trigger: 'item'
            },
            legend: {
                top: '5%',
                left: 'center'
            },
            series: [
                {
                    name: '居民年龄',
                    type: 'pie',
                    radius: ['40%', '70%'],
                    avoidLabelOverlap: false,
                    itemStyle: {
                        borderRadius: 10,
                        borderColor: '#fff',
                        borderWidth: 2
                    },
                    label: {
                        show: false,
                        position: 'center'
                    },
                    emphasis: {
                        label: {
                            show: true,
                            fontSize: 30,
                            fontWeight: 'bold'
                        }
                    },
                    labelLine: {
                        show: false
                    },
                    data: []
                }
            ]

        })
        await getresidentagelist();
        residentage.setOption({
            series: [
                {
                    data: residentagelist.value.map(item => ({ value: item.resident_count, name: item.age_group }))
                }
            ]

        })

        //culture
        const residentculture = echarts.init(document.getElementById('residentculture'));
        residentculture.setOption({
            tooltip: {
                trigger: 'item'
            },
            legend: {
                top: '5%',
                left: 'center'
            },
            series: [
                {
                    name: '居民文化',
                    type: 'pie',
                    radius: ['40%', '70%'],
                    avoidLabelOverlap: false,
                    itemStyle: {
                        borderRadius: 10,
                        borderColor: '#fff',
                        borderWidth: 2
                    },
                    label: {
                        show: false,
                        position: 'center'
                    },
                    emphasis: {
                        label: {
                            show: true,
                            fontSize: 30,
                            fontWeight: 'bold'
                        }
                    },
                    labelLine: {
                        show: false
                    },
                    data: []
                }
            ]

        })
        await getresidentculturelist();
        residentculturelist.value.map(item => {
            switch (item.culture) {
                case 1:
                    item.culture = '初中/中专';
                    break;
                case 2:
                    item.culture = '高中';
                    break;
                case 3:
                    item.culture = '本科';
                    break;
                case 4:
                    item.culture = '研究生';
                    break;
                case 5:
                    item.culture = '博士';
                    break;
                default:
                    item.culture = '不详';
                    break;
            }
        })
        residentculture.setOption({
            series: [
                {
                    data: residentculturelist.value.map(item => ({ value: item.num, name: item.culture }))
                }
            ]
        })
        //sex
        const residentsex = echarts.init(document.getElementById('residentsex'))
        residentsex.setOption({
            tooltip: {
                trigger: 'item'
            },
            legend: {
                top: '5%',
                left: 'center'
            },
            series: [
                {
                    name: '居民性别',
                    type: 'pie',
                    radius: ['40%', '70%'],
                    avoidLabelOverlap: false,
                    itemStyle: {
                        borderRadius: 10,
                        borderColor: '#fff',
                        borderWidth: 2
                    },
                    label: {
                        show: false,
                        position: 'center'
                    },
                    emphasis: {
                        label: {
                            show: true,
                            fontSize: 30,
                            fontWeight: 'bold'
                        }
                    },
                    labelLine: {
                        show: false
                    },
                    data: []
                }
            ]
        })
        await getresidentsexlist();
        residentsexlist.value.map(item => {
            switch (item.sex) {
                case 0:
                    item.sex = '男';
                    break;
                case 1:
                    item.sex = '女';
                    break;
                case 2:
                    item.sex = '未知';
                    break;
                default:
                    item.sex = '未知';
                    break;
            }
        })
        residentsex.setOption({
            series: [
                {
                    data: residentsexlist.value.map(item => ({ value: item.num, name: item.sex }))
                }
            ]
        })
//tag
const residenttag = echarts.init(document.getElementById('residenttag'))
residenttag.setOption({
    title: {
    text: '居民标签'
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  legend: {},
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'value',
    boundaryGap: [0, 0.01]
  },
  yAxis: {
    type: 'category',
    data: ['Brazil', 'Indonesia', 'USA', 'India', 'China', 'World']
  },
  series: [
  
    {
      name: '2012',
      type: 'bar',
      data: [19325, 23438, 31000, 121594, 134141, 681807]
    }
  ]
})
await getresidenttaglist();
let tags=residenttaglist.value.map(item => (item.tag_name))
let nums=residenttaglist.value.map(item => (item.num))
console.log('tags',tags);
console.log('nums',nums);
residenttag.setOption({
    yAxis: {
    type: 'category',
    data:tags
  },
  series: [
  
    {
      name: '居民标签',
      type: 'bar',
      data: nums
    }
  ]
})


//package
const residentservicepackageuse=echarts.init(document.getElementById('residentservicepackageuse'))
residentservicepackageuse.setOption({
    title: {
    text: '服务包使用情况'
  },
    tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: [
    {
      type: 'category',
      data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
      axisTick: {
        alignWithLabel: true
      }
    }
  ],
  yAxis: [
    {
      type: 'value'
    }
  ],
  series: [
    {
      name: 'Direct',
      type: 'bar',
      barWidth: '60%',
      data: [10, 52, 200, 334, 390, 330, 220]
    }
  ]
})

await getresidentservicepackagelist();
 let name= residentservicepackagelist.value.map(item=>(item.name))
 let num=residentservicepackagelist.value.map(item=>(item.num))
 residentservicepackageuse.setOption({
    xAxis: [
    {
      type: 'category',
      data: name,
      axisTick: {
        alignWithLabel: true
      }
    }
  ],
  series: [
    {
      name: '',
      type: 'bar',
      barWidth: '60%',
      data: num
    }
  ]
 })
    });
});


</script>
<style scoped>
.cardbg {
    width: 100%;
    height: 100%;
    background-color: #f2f7fb;
    display: flex;
    justify-content: center;
    align-items: center;
}

.card {
    /* 圆角 */
    border-radius: 10px;
    width: 80%;
    height: 100%;
    background-color: white;
    padding: 20px;
}

.residentage {
    width: 25%;
    height: 350px;
    padding: 10px;

}

.resi {
    width: 100%;
    height: 100%;
}

.ca:hover {
    /* 鼠标悬停时阴影消失 */
    box-shadow: none;
}

.ca {

    box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.1), 0 3px 10px 0 rgba(0, 0, 0, 0.09);
    transition: box-shadow 0.3s ease;
}
</style>